#import "DataEyeSDKHelper.h"
#import "HttpServer.h"
#import "DataEyeSDK.h"
#import "UserNotifications/UserNotifications.h"
#import <AdSupport/ASIdentifierManager.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import "CustomAppController.h"

@implementation CustomAppController

- (void)startUnity:(UIApplication *)application{
    [super startUnity:application];
    
    NSLog(@"初始化H5 SDK");
    // self.appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    // NSLog(@"app version:%@", self.appVersion);
    // self.h5 = [[Veiled alloc] init];
    // [self.h5 i:self.rootView];
    // [self.h5 set:self.appVersion];
    // [self.h5 getData];
    // [self.h5 get5ac];
//    self.rootView.alpha = 0.5;  测试代码，正式注释掉
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions{
    [super application:application didFinishLaunchingWithOptions:launchOptions];
    NSLog(@"初始化BI");
    // 初始化BI
    [[DataEyeSDKHelper sharedInstance] initializeDataEyes];

    // h5上报
    // [self.h5 setReportFun:^(NSString *str, NSDictionary *info) {
    //   [[DataEyeSDK sharedInstance] track:str properties:info];
    // }];

    // 获取IDFA
    if (@available(iOS 14, *)) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)),dispatch_get_main_queue(),^{
              [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                    if (status ==
                        ATTrackingManagerAuthorizationStatusAuthorized) {
                        self.idfa =[[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                    } else {
                        NSLog(@"Please allow App request tracking in Settings-Privacy-Tracking");
                    }
              }];
        });
    } else {
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            self.idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
        } else {
            NSLog(@"Please allow App request tracking in Settings-Privacy-Tracking");
        }
    }
    NSLog(@"原生获取idfa:%@", self.idfa);
    return YES;
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"初始化设备token");
    NSUInteger length = deviceToken.length;
    const unsigned char *buffer = (const unsigned char *)deviceToken.bytes;
    NSMutableString *token = [NSMutableString stringWithCapacity:(length * 2)];
    for (int i = 0; i < length; ++i) {
        [token appendFormat:@"%02x", buffer[i]];
    }
    self.deviceToken = token;
    NSLog(@"原生获取设备token:%@", self.deviceToken);
    
//    // 创建 MyHttpServer 实例
//    HttpServer *httpServer = [[HttpServer alloc] init];
//
//    // 定义URL和请求参数
//    NSString *urlString = @"https://dstm.sladegames.com/u/bind_device";
//    NSDictionary *postData = @{
//        @"device_token" : token,
//        @"device_id" : [[DataEyeSDK sharedInstance] getDeviceId]
//    };
//    NSString *key = @"d6aa9b4ac0d2490ba99aab220ca5b1ba";
//    NSString *productName = @"Dog Express: Merge and Puzzle";
//
//    [httpServer
//        sendPOSTRequestWithURLString:urlString
//                            postData:postData
//                                 key:key
//                               pName:productName
//                   completionHandler:^(NSData *data, NSURLResponse *response,
//                                       NSError *error) {
//                     if (error) {
//                         // 处理错误
//                         NSLog(@"Error-Bind: %@", error.localizedDescription);
//                     } else {
//                         // 处理响应数据
//                         NSLog(@"Response-Bind: %@", response);
//                         // 例如，如果返回的是JSON数据：
//                         NSError *jsonError;
//                         NSDictionary *jsonResponse = [NSJSONSerialization
//                             JSONObjectWithData:data
//                                        options:0
//                                          error:&jsonError];
//                         if (!jsonError) {
//                             NSLog(@"Response JSON: %@", jsonResponse);
//                         } else {
//                             NSLog(@"JSON Error: %@",
//                                   jsonError.localizedDescription);
//                         }
//                     }
//                   }];
}

//- (void)application:(UIApplication *)app
//    didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
//    NSString *error_str = [NSString stringWithFormat:@"%@", error];
//    NSLog(@"Failed to get token, error:%@", error_str);
//}

//// 处理前台接收到的通知
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center
//       willPresentNotification:(UNNotification *)notification
//         withCompletionHandler:
//             (void (^)(UNNotificationPresentationOptions))completionHandler {
//    // 在应用程序处于前台时显示通知
//    //  completionHandler(UNNotificationPresentationOptionAlert |
//    //  UNNotificationPresentationOptionBadge |
//    //  UNNotificationPresentationOptionSound);
//    // 在前台时不显示通知
//    completionHandler(UNNotificationPresentationOptionNone);
//}
//
//// 处理用户与通知的交互
//- (void)userNotificationCenter:(UNUserNotificationCenter *)center
//    didReceiveNotificationResponse:(UNNotificationResponse *)response
//             withCompletionHandler:(void (^)())completionHandler {
//    // 处理用户点击通知后的操作
//
//    completionHandler();
//    NSDictionary *userInfo = response.notification.request.content.userInfo;
//    // 提取 path 值
//    NSString *path = userInfo[@"path"];
//    NSString *str = [path copy];
//
//    NSLog(@"获取的path: %@", str);
//
//    const char *myStr = [str UTF8String];
//    UnitySendMessage("CallbackReceiver", "JumpToPath", myStr);
//    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
//}

@end
